<template>
  <PageWrapper dense contentClass="p-16px">
    <Card>
      <div class="flex items-center justify-between">
        <div class="flex items-center">
          <Image :width="64" :height="64" :preview="false"
            src="https://zos.alipayobjects.com/rmsportal/jkjgkEfvpUPVyRjUImniVslZfWPnJuuZ.png" />
          <div class="h-64px flex flex-col justify-between ml-16px">
            <div class="flex items-center">
              <h3 class="mr-6px mb-0">{{ state.customerInfo.customerName }}</h3>
              <HeartTwoTone :twoToneColor="state.customerInfo.followStatus ? '#fadb14' : ''" />
            </div>
            <div>
              <template v-for="tag in state.customerLabel" :key="tag">
                <Tooltip v-if="tag.length > 20" :title="tag">
                  <Tag :closable="false" color="blue" @close="handleClose(tag)">
                    {{ `${tag.slice(0, 20)}...` }}
                  </Tag>
                </Tooltip>
                <Tag v-else :closable="fale" color="blue" @close="handleClose(tag)">
                  {{ tag }}
                </Tag>
              </template>
              <!-- <Input
                v-if="state.inputVisible"
                ref="inputRef"
                type="text"
                size="small"
                :style="{ width: '78px' }"
                v-model:value="state.inputValue"
                @blur="handleInputConfirm"
                @keyup.enter="handleInputConfirm"
              />
              <Tag v-else @click="showInput" style="background: #fff; border-style: dashed">
                <plus-outlined />
                新增标签
              </Tag> -->
            </div>
          </div>
        </div>
        <Space>
          <Button @click="handleCancel">返回</Button>
          <Button @click="handleEdit">编辑</Button>
          <Dropdown>
            <template #overlay>
              <Menu @click="handleMenuClick">
                <MenuItem key="1">销售订单</MenuItem>
                <MenuItem key="2">销售退款</MenuItem>
              </Menu>
            </template>
            <Button @click.prevent type="primary">新建关联
              <DownOutlined />
            </Button>
          </Dropdown>
          <Dropdown>
            <template #overlay>
              <Menu @click="handleMenuClick">
                <MenuItem key="3">移交</MenuItem>
                <MenuItem key="4">删除</MenuItem>
              </Menu>
            </template>
            <Button @click.prevent>
              <SmallDashOutlined />
            </Button>
          </Dropdown>
        </Space>
      </div>
      <Divider />
      <Description v-if="!isEmpty(state.contactVoMain)" :column="3" :bordered="false" :data="state.contactVoMain"
        :schema="schema" />
      <Tabs v-model:activeKey="state.activeKey">
        <TabPane key="1" tab="基本信息">
          <Row>
            <Col :span="16">
            <BaseInfo :customerInfo="state.customerInfo" />
            </Col>
            <Col :span="1" style="text-align: center">
            <Divider type="vertical" style="height: 100%" />
            </Col>
            <Col :span="7">
            <Abstract :customerInfo="state.customerInfo" />
            </Col>
          </Row>
          <CollapseContainer title="联系人" class="mt-8px">
            <Contact :recordId="state.customerInfo.customerId" type="customer" />
          </CollapseContainer>
        </TabPane>
        <TabPane key="2" tab="相关信息">
          <RelevantInformation />
        </TabPane>
        <TabPane key="3" tab="地址" forceRender>
          <Address :recordId="state.customerInfo.customerId" />
        </TabPane>
        <TabPane key="4" tab="附件">
          <FileList />
        </TabPane>
        <TabPane key="5" tab="操作日志">
          <Log title="客户" />
        </TabPane>
      </Tabs>
    </Card>
  </PageWrapper>
</template>

<script setup lang="ts">
import { onMounted, ref, reactive, nextTick, createVNode } from 'vue';
import { getCustomer, delCustomer } from '@/api/customer';
import {
  Tag,
  // Rate,
  Tooltip,
  Input,
  Card,
  Image,
  Space,
  Button,
  Dropdown,
  Menu,
  Divider,
  Tabs,
  Row,
  Col,
  Modal,
} from 'ant-design-vue';
import { Description, DescItem } from '@/components/Description/index';
import { useTabs } from '@/hooks/web/useTabs';
import { useGo } from '@/hooks/web/usePage';
import { PageEnum } from '@/enums/pageEnum';
import { CollapseContainer } from '@/components/Container';
import { PageWrapper } from '@/components/Page';
import { Address } from '@/components/Address';
import { Contact } from '@/components/Contact';
import { FileList } from '@/components/FileList';
import { Log } from '@/components/Log';
import BaseInfo from './components/baseInfo.vue';
import Abstract from './components/abstract.vue';
import RelevantInformation from './components/relevantInformation.vue';
import type { MenuInfo } from 'ant-design-vue/lib/menu/src/interface';
import { isEmpty } from '@/utils/is';
import { useUserStoreWithOut } from '@/store/modules/user';
import {
  PlusOutlined,
  HeartTwoTone,
  SmallDashOutlined,
  DownOutlined,
  ExclamationCircleOutlined,
} from '@ant-design/icons-vue';
import { useRoute } from 'vue-router';
/** 拿到路由的id */
const route = useRoute();
const customerId = route.query.id as string;
defineOptions({ name: 'CustomerDetail' });
const MenuItem = Menu.Item;
const TabPane = Tabs.TabPane;
const userStore = useUserStoreWithOut();
const emit = defineEmits(['register', 'reload']);
const { closeCurrent } = useTabs();
const inputRef = ref();
const state = reactive({
  customerLabel: [],
  inputVisible: false,
  inputValue: '',
  activeKey: '1',
  customerInfo: {},
  contactVoMain: {},
});
const schema: DescItem[] = [
  {
    field: 'contactName',
    label: '主联系人',
  },
  {
    field: 'contactTel',
    label: '联系人电话',
  },
  {
    field: 'contactEmail',
    label: '联系人邮箱',
  },
  // {
  //   field: 'customerAlias',
  //   label: '添加时间',
  //   render: (curVal) => {
  //     return '2023-08-02 12:49';
  //   },
  // },
  // {
  //   field: 'customerCountryId',
  //   label: '负责人',
  //   render: (curVal) => {
  //     return '金晨曦';
  //   },
  // },
];
const handleClose = (removedTag: string) => {
  const customerLabel = state.customerLabel.filter((tag) => tag !== removedTag);
  state.customerLabel = customerLabel;
};

const showInput = () => {
  state.inputVisible = true;
  nextTick(() => {
    inputRef.value.focus();
  });
};

const handleInputConfirm = () => {
  const inputValue = state.inputValue as never;
  let customerLabel = state.customerLabel;
  if (inputValue && customerLabel.indexOf(inputValue) === -1) {
    customerLabel = [...customerLabel, inputValue];
  }
  console.log(customerLabel);
  Object.assign(state, {
    customerLabel,
    inputVisible: false,
    inputValue: '',
  });
};
const handleMenuClick = (e: MenuInfo) => {
  switch (e.key) {
    case '4':
      handleDelete();
      break;

    default:
      break;
  }
};
const handleDelete = () => {
  Modal.confirm({
    title: '删除',
    icon: createVNode(ExclamationCircleOutlined),
    content: '你确定要删除当前客户吗？',
    okText: '确认',
    cancelText: '取消',
    onOk: async () => {
      await delCustomer(state.customerInfo.customerId);
      handleCancel();
    },
  });
};
const go = useGo();
function handleEdit() {
  closeCurrent();
  go({
    path: '/customer/customerEdit' as PageEnum,
    query: { id: customerId, type: 'update' },
  });
}
function handleCancel() {
  closeCurrent();
  go({ path: '/customer/customer' as PageEnum });
}
const getUserInfo = async () => {
  const res = (await getCustomer(customerId)) as any;
  res.followStatus =
    res.followerIds.split(',').findIndex((item) => item == userStore.userInfo?.userId) > -1;
  state.customerLabel = res.customerLabel.split(',');
  state.customerInfo = res;
  const list = res.contactVoList.filter((item) => item.contactIsMain == 1);
  if (list.length) {
    state.contactVoMain = list[0];
  }
};
onMounted(() => {
  getUserInfo();
});
</script>

<style lang="less" scoped>
:deep(.ant-tag) {
  margin-right: 6px;
}

:deep(.ant-card-body) {
  padding: 16px;
}
</style>
